//给搜索框添加value值
function wlhref() {
  const params = new URLSearchParams(window.location.search)
  const keys = params.get('search')
  if (keys !== null) {
    const value = decodeURIComponent(keys)
    const searchInput = document.querySelector('.search-form-input')
    if (searchInput) {
      searchInput.value = value
    }
  }
}
wlhref('search')

//板块函数
function board() {
  let line = document.querySelector('.search-top .line')
  let board = document.querySelector('.board')
  let centerArticle = document.querySelector('.center-article')
  let shuxian = document.querySelector('.search-top .shuxian')
  let sort = document.querySelector('.search .sort')
  line.style.left = '35px'
  shuxian.classList.remove('spanActive')
  document.querySelector('.search-top .liebiao').classList.add('spanActive')
  board.style.display = 'flex'
  centerArticle.style.display = 'none'
  sort.style.display = 'none'
  document.querySelector('.search-form-input').placeholder = '输入要搜索的板块'
  document.querySelector('.search-form-input').value = ''
  document.cookie = "wenzhang=false; path=/"
  document.querySelector('.search-form-type').value = 'bd'
  wlhref('search')
}

//文章函数
function article() {
  let line = document.querySelector('.search-top .line')
  let board = document.querySelector('.board')
  let centerArticle = document.querySelector('.center-article')
  let liebiao = document.querySelector('.search-top .liebiao')
  let sort = document.querySelector('.search .sort')
  line.style.left = '100px'
  liebiao.classList.remove('spanActive')
  document.querySelector('.search-top .shuxian').classList.add('spanActive')
  centerArticle.style.display = 'flex'
  sort.style.display = 'flex'
  board.style.display = 'none'
  document.querySelector('.search-form-input').placeholder = '输入要搜索的文章';
  document.cookie = "wenzhang=true; path=/"
  document.querySelector('.search-form-type').value = 'wz'
  wlhref('search')
}

//板块点击事件
document.querySelector('.search-top .liebiao').addEventListener('click', () => {
  window.location.href = '../view/index.php'
  board()
})
//文章点击事件
document.querySelector('.search-top .shuxian').addEventListener('click', () => {
  window.location.href = '../view/index.php?sort=hot'
  article()
})

//获取cookie值函数
function getCookie(key) {
  return document.cookie.split(';').map(item => item.trim()).find(item => item.startsWith(key + '='))?.split('=')[1];
}

// document.cookie = 'wenzhang=false; path=/'
//判断是文章还是板块
let cookie = getCookie('wenzhang')
if (cookie == 'true') {
  article()
} else {
  board()
}


//内容点击事件
document.querySelector('.content').addEventListener('click', function (e) {
  if (e.target === this) {
    this.style.right = '-150vw';
    history.pushState({}, '', window.location.pathname);
    initBdArt();
  }
});
//登录模态框
if (document.querySelector('.header-login')) {
  document.querySelector('.header-login').addEventListener('click', () => {
    document.querySelector('.modal').style.display = 'flex'
  })
}
document.querySelector('.icon-cha').addEventListener('click', () => {
  document.querySelector('.modal').click()
})
document.querySelector('.modal').addEventListener('click', function (e) {
  if (e.target == this) {
    this.style.display = 'none'
  }
})

//用户退出模态框
document.querySelector('.user-out').addEventListener('click', () => {
  document.querySelector('.modal-out').style.display = 'flex'
})
document.querySelector('.modal-out').addEventListener('click', function (e) {
  if (e.target == this) {
    this.style.display = 'none'
  }
})

//注册登录切换
document.querySelector('.icon-zhuce').addEventListener('click', function () {
  let line = document.querySelector('.line')
  let login = document.querySelector('.icon-denglu-copy')
  let loginPage = document.querySelector('.login')
  let regist = document.querySelector('.regist')
  line.style.left = '80px'
  login.classList.remove('list-active')
  this.classList.add('list-active')
  regist.style.display = 'block'
  loginPage.style.display = 'none'
})
document.querySelector('.icon-denglu-copy').addEventListener('click', function () {
  let line = document.querySelector('.line')
  let zhuce = document.querySelector('.icon-zhuce')
  let loginPage = document.querySelector('.login')
  let regist = document.querySelector('.regist')
  line.style.left = '10px'
  zhuce.classList.remove('list-active')
  this.classList.add('list-active')
  loginPage.style.display = 'block'
  regist.style.display = 'none'
})
document.querySelector('.goReg').addEventListener('click', () => {
  document.querySelector('.icon-zhuce').click()
})


//注册时显示头像
document.querySelector('.regist #avatar').addEventListener('change', function () {
  let file = this.files[0] // 获取选中的文件  
  let reader = new FileReader() // 创建FileReader对象  
  reader.onload = function (e) {
    console.log(e.target.result)
    document.querySelector('.regist .avatar img').src = e.target.result
  };
  reader.readAsDataURL(file) // 将文件读取为Data URL
})


//用户登录之后的下拉框
if (document.querySelector('.user-logining')) {
  document.querySelector('.user-logining').addEventListener('click', () => {
    let user = document.querySelector('.user')
    if (!user.classList.contains('user-active')) {
      user.classList.add('user-active')
    } else {
      user.classList.remove('user-active')
    }
  })

}



//搜索排序，全部文章排序
document.querySelectorAll('.sort .iconfont').forEach(item => {
  item.addEventListener('click', function () {
    const params = new URLSearchParams(window.location.search)
    const sortType = params.get('search')
    if (sortType != null) {
      let paramObj = { sort: this.getAttribute('data-sort'), search: sortType, searchtype: 'wz' }
      let params = `?search=${sortType}&searchtype=wz&sort=${this.getAttribute('data-sort')}`
      sortReqFn(params, paramObj)
    } else {
      let paramObj = { sort: this.getAttribute('data-sort') }
      let params = `?sort=${this.getAttribute('data-sort')}`
      sortReqFn(params, paramObj)
    }
    initSort()
  })
})

//排序请求函数
function sortReqFn(params, paramObj) {
  const newUrl = window.location.pathname + `${params}`
  history.pushState(paramObj, '', newUrl)
  $.ajax({
    url: 'index.php',
    type: 'GET',
    data: paramObj,
    success: function (response) {
      // 解析响应并更新页面
      const parser = new DOMParser()
      const doc = parser.parseFromString(response, 'text/html')
      const newContent = doc.querySelector('.center-article').innerHTML
      document.querySelector('.center-article').innerHTML = newContent
    },
    error: function (xhr, status, error) {
      console.error('请求失败:', status, error)
    }
  })
}
//初始化排序样式函数
function initSort() {
  const params = new URLSearchParams(window.location.search)
  const sortType = params.get('sort')
  let activeIndex = 0
  if (sortType === 'hot') activeIndex = 0
  else if (sortType === 'now') activeIndex = 1
  else if (sortType === 'look') activeIndex = 2
  sortList(activeIndex)
}
function sortList(index) {
  document.querySelectorAll('.sort .iconfont').forEach((item, i) => {
    item.classList.toggle('sortActive', i === index)
  })
}
initSort()


document.querySelectorAll('.center-article-item').forEach(item => {
  item.addEventListener('click', () => {
    document.querySelector('.article').style.right = '0vw'
  })
})

document.querySelector('.article').addEventListener('click', function (e) {
  if (e.target == this) {
    const sort = new URLSearchParams(window.location.search).get('sort')
    const bid = new URLSearchParams(window.location.search).get('bid')
    const search = new URLSearchParams(window.location.search).get('search')
    let url = window.location.pathname
    if (sort != null) {
      if (search != null) {
        url = url + `?search=${search}&searchtype=wz&sort=${sort}`
      } else {
        url = url + `?sort=${sort}`
      }
    }
    if (bid != null) {
      url = url + `?bid=${bid}`
    }
    document.cookie = "aid=;path=/"
    history.pushState({}, '', url);
    this.style.right = '-150vw'
  }
})



//添加文章跳转页面
document.querySelector('.right-add').addEventListener('click', () => {
  console.log(getCookie('user'))
  if (getCookie('user') != undefined && getCookie('user') != '') {
    window.location.href = 'http://127.0.0.1:8080/speakUp/view/addArtIndex.php'
  } else {
    document.querySelector('.dzErr').style.transform = 'translateY(0px)'
  }
})

document.querySelector('.dzErr i').addEventListener('click', function () {
  this.parentNode.style.transform = 'translateY(-100px)'
})



document.addEventListener('click', (e) => {
  //点赞功能
  if (e.target.closest('.icon-dianzan') || e.target.closest('.icon-dianzan_kuai')) {
    const dzBtn = e.target.closest('.icon-dianzan, .icon-dianzan_kuai');
    let uname = getCookie('user')
    if (!uname) return errMsg('请登录')
    let aid = new URLSearchParams(window.location.search).get('aid')
    $.ajax({
      url: "../control/like",
      type: 'post',
      data: { uname, aid },
      success: (res) => {
        if (res.code === 200) {

          dzBtn.classList.toggle('icon-dianzan', !res.liked)
          dzBtn.classList.toggle('icon-dianzan_kuai', res.liked)
          const likeCountEl = dzBtn.parentNode.querySelector('span')
          // console.log(likeCountEl)
          if (likeCountEl) {
            const currentCount = parseInt(likeCountEl.textContent)
            likeCountEl.textContent = res.liked ? currentCount + 1 : currentCount - 1
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        errMsg(err)
      }
    })
  }

  //评论按钮
  if (e.target.closest('.sendbtn')) {
    let sendBtn = e.target.closest('.sendbtn')
    let text = sendBtn.parentNode.querySelector('textarea')
    let zshu = sendBtn.parentNode.querySelector('.textNum .wordCount')
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')
    if (text.value.trim().length <= 0) {
      errMsg('请输入评论的内容')
      return
    }

    $.ajax({
      url: '../control/userCom.php',
      type: 'post',
      data: { aid, uname, content: text.value.trim() },
      success: (res) => {
        if (res.code == 200) {
          let nr = document.querySelector('.user-parent-comment').innerHTML
          document.querySelector('.user-parent-comment').innerHTML = `
                 <li class="user-reply" data-cid="${res.cid}" data-who="${res.whoid}">
        <div class="user-reply-main">
          <div class="user-reply-top">
            <span>${uname}</span>
            <span>刚刚</span>
          </div>
          <p>${text.value.trim()}</p>
          <div class="user-reply-footer">
      
            <span class="replySpan">回复</span>
            <span class='delCom'>删除</span>
          </div>
          <div class="user-reply-footer-com">
            <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
            <button class="repBtn"><i class="iconfont icon-fasong"></i>回复</button>
            <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
          </div>
        </div>
        <ul class="user-reply-son"></ul>
        </li>
                `+ nr
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          zshu.textContent = 0
          text.value = ''
        } else {
          errMsg(res.msg)
        }
      }, error: (err) => {
        console.log(err)
        errMsg(err.message)
      }
    })
  }

  // 回复按钮展示
  if (e.target.closest(".replySpan")) {
    let repSpan = e.target.closest(".replySpan")
    if (!repSpan) {
      return
    }

    let main = repSpan.parentNode.parentNode.querySelector('.user-reply-footer-com')
    if (main.classList.contains('ractive')) {
      main.classList.remove('ractive')
    } else {
      document.querySelectorAll('.ractive').forEach(item => {
        item.classList.remove('ractive')
      })
      main.classList.add('ractive')
    }


  }

  //回复评论按钮
  if (e.target.closest(".repBtn")) {
    let repBtn = e.target.closest(".repBtn")
    if (!repBtn) {
      return
    }
    // console.log(repBtn.parentNode.parentNode.parentNode)
    let li = repBtn.parentNode.parentNode.parentNode
    let text = repBtn.parentNode.querySelector('textarea')
    let zshu = repBtn.parentNode.querySelector('.textNum .wordCount')
    if (text.value.trim().length <= 0) return errMsg('回复信息不能为空')

    let cid = li.dataset.cid
    let content = text.value.trim()
    let who = li.dataset.who
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')
    $.ajax({
      url: "../control/userRep.php",
      type: 'post',
      data: { cid, content, who, aid, uname },
      success: (res) => {
        if (res.code == 200) {
          const replyList = li.querySelector('.user-reply-son')
          replyList.innerHTML += `
              <li class="son-reply" data-cid="${cid}" data-who="${res.uid}" data-rid ="${res.rid}">
                <div class="son-reply-main">
                  <div class="son-reply-top">
                    <span>${getCookie('user')} <span>:回复${res.uname}</span></span>
                    <span>刚刚</span>
                  </div>
                  <p>${content}</p>
                  <div class="son-reply-footer">
                    <span>回复</span>
                    <span class='delRep'>删除</span>
                  </div>
                  <div class="son-reply-footer-com">
                    <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
                    <button class="sonRepBtn"><i class="iconfont icon-fasong"></i>回复</button>
                    <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
                  </div>
                </div>
              </li>
            `
          repBtn.parentNode.parentNode.querySelector('.user-reply-footer').innerHTML += `<span class="shou"><i class="iconfont icon-xiangxia1"></i></span>`
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          text.value = ''
          zshu.textContent = 0
          document.querySelectorAll('.ractive').forEach(item => {
            item.classList.remove('ractive')
          })
          if (!replyList.classList.contains('hactive')) {
            replyList.classList.add('hactive')
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        console.log(err)
      }
    })

  }

  //展开回复按钮
  if (e.target.closest(".shou")) {
    let span = e.target.closest(".shou")
    if (!span) return
    let ul = span.parentNode.parentNode.parentNode.querySelector('.user-reply-son')
    if (ul.classList.contains('hactive')) {
      ul.classList.remove('hactive')
    } else {
      ul.classList.add('hactive')
    }
  }

  //展开回复回复按钮
  if (e.target.closest(".son-reply-footer span:nth-child(1)")) {
    let sonRep = e.target.closest(".son-reply-footer")
    if (!sonRep) return
    let li = sonRep.parentNode.parentNode
    let repBox = li.querySelector('.son-reply-footer-com')
    if (repBox.classList.contains('ractive')) {
      repBox.classList.remove('ractive')
    } else {
      document.querySelectorAll('.ractive').forEach(item => {
        item.classList.remove('ractive')
      })
      repBox.classList.add('ractive')
    }
  }
  //回复回复按钮
  if (e.target.closest('.sonRepBtn')) {
    let sonRepBtn = e.target.closest('.sonRepBtn')
    if (!sonRepBtn) return
    console.log(sonRepBtn)
    let li = sonRepBtn.parentNode.parentNode.parentNode
    let text = sonRepBtn.parentNode.querySelector('textarea')
    let zshu = sonRepBtn.parentNode.querySelector('.textNum .wordCount')
    if (text.value.trim().length <= 0) return errMsg('回复消息不能为空')

    let cid = li.dataset.cid
    let content = text.value.trim()
    let who = li.dataset.who
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')

    $.ajax({
      url: '../control/userRep.php',
      type: 'post',
      data: { cid, content, who, aid, uname },
      success: (res) => {
        if (res.code == 200) {
          let ul = li.parentNode
          // console.log(ul)
          ul.innerHTML += `
              <li class="son-reply" data-cid="${cid}" data-who="${res.uid}" data-rid ="${res.rid}">
                <div class="son-reply-main">
                  <div class="son-reply-top">
                    <span>${getCookie('user')} <span>:回复${res.uname}</span></span>
                    <span>刚刚</span>
                  </div>
                  <p>${content}</p>
                  <div class="son-reply-footer">
                    <span>回复</span>
                    <span class='delRep'>删除</span>
                  </div>
                  <div class="son-reply-footer-com">
                    <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
                    <button class="sonRepBtn"><i class="iconfont icon-fasong"></i>回复</button>
                    <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
                  </div>
                </div>
              </li>
            `;
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          text.value = ''
          zshu.textContent = 0
          document.querySelectorAll('.ractive').forEach(item => {
            item.classList.remove('ractive')
          })
          if (!ul.classList.contains('hactive')) {
            ul.classList.add('hactive')
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        console.log(err)
      }
    })
  }
})



document.querySelectorAll('.artLi').forEach(item => {
  item.addEventListener('click', function () {
    // console.log(this)
    // console.log(user)
    let user = getCookie('user')
    if (user && user.trim() != '') {
      this.querySelector('i').innerHTML++
    }
    document.querySelector('.article').style.right = '0vw'
  })
})


//板块文章请求函数
function reqBdArtfn(params, paramObj, el, initFn) {
  const newUrl = window.location.pathname + `${params}`
  history.pushState(paramObj, '', newUrl)
  $.ajax({
    url: 'index.php',
    type: 'GET',
    data: paramObj,
    success: function (response) {
      const parser = new DOMParser()
      const doc = parser.parseFromString(response, 'text/html')
      const newContent = doc.querySelector(`${el}`).innerHTML
      document.querySelector(`${el}`).innerHTML = newContent
      initFn()
    },
    error: function (xhr, status, error) {
      console.error('请求失败:', status, error)
    }
  })
}
// 板块中的文章请求
document.querySelectorAll('.board .board-item').forEach(item => {
  item.addEventListener('click', function () {
    let params = `?bid=${this.getAttribute('data-bid')}`
    let paramObj = { bid: this.getAttribute('data-bid') }
    let el = '.content'
    reqBdArtfn(params, paramObj, el, initBdArt)
  })
})



// 板块中文章的详细请求
document.querySelector('.content').addEventListener('click', function (e) {
  if (e.target.closest('.box-article-list .list-item')) {
    const item = e.target.closest('.list-item');
    const bid = new URLSearchParams(window.location.search).get('bid')
    let params = `?bid=${bid}&aid=${item.getAttribute('data-art')}`
    let paramObj = { bid: bid, aid: item.getAttribute('data-art') }
    let el = '.article'
    let user = getCookie('user')
    let li = item.querySelector('.icon-yanjing_xianshi')
    if (user && user.trim() != '') {
      li.innerHTML++
    }
    reqBdArtfn(params, paramObj, el, initArt)
  }
})

// 文章的详细请求函数
function artFn(item, dataSet) {
  const sort = new URLSearchParams(window.location.search).get('sort')
  const search = new URLSearchParams(window.location.search).get('search')
  let params = null
  let paramObj = null
  if (sort != null) {
    params = `?sort=${sort}&aid=${item.getAttribute(`data-${dataSet}`)}`
    paramObj = { sort: sort, aid: item.getAttribute(`data-${dataSet}`) }
  } else {
    params = `?aid=${item.getAttribute(`data-${dataSet}`)}`
    paramObj = { aid: item.getAttribute(`data-${dataSet}`) }
  }
  if (search != null) {
    params = `?search=${search}&searchtype=wz&sort=${sort}&aid=${item.getAttribute(`data-${dataSet}`)}`
    paramObj = { search: search, searchtype: 'wz', sort: sort, aid: item.getAttribute(`data-${dataSet}`) }
  }
  let el = '.article'
  reqBdArtfn(params, paramObj, el, initArt)
}

//文章的详细请求
document.querySelector('.center-article').addEventListener('click', (e) => {
  if (e.target.closest('.center-article-item')) {
    const item = e.target.closest('.center-article-item')
    let user = getCookie('user')
    let li = item.querySelector('.icon-yanjing_xianshi')
    if (user && user.trim() != '') {
      li.innerHTML++
    }
    artFn(item, 'art')
  }

})

//右侧文章详情展示
document.querySelector('.right-article ul').addEventListener('click', (e) => {
  if (e.target.closest('.artLi')) {
    const item = e.target.closest('.artLi')
    artFn(item, 'artId')
  }

})

// 文章展示样式函数
function initArt() {
  const params = new URLSearchParams(window.location.search)
  const aid = params.get('aid')
  if (aid != null && aid != '') {
    document.cookie = "aid=yes;path=/"
    document.querySelector('.article').style.right = '0vw'
    // console.log(getCookie('aid'))
  } else {
    document.cookie = "aid=;path=/"
    document.querySelector('.article').style.right = '-150vw'
    // console.log(getCookie('aid'))
  }
}
initArt()

// 板块中文章展示样式函数
function initBdArt() {
  const params = new URLSearchParams(window.location.search)
  const bid = params.get('bid')
  if (bid != null && bid != '') {
    document.querySelector('.content').style.right = '0vw'
  } else {
    document.querySelector('.content').style.right = '-150vw'
  }
}
initBdArt()



//详细页面发布评论字数显示
document.querySelector('.article').addEventListener('input', (e) => {
  let textareaC = e.target.closest('.box-reply-inp textarea')
  let textareaR = e.target.closest('.ractive textarea') || null

  if (textareaC) {
    document.querySelector('.wordCount').textContent = textareaC.value.trim().length
  }
  if (textareaR) {
    document.querySelector('.ractive .wordCount').textContent = textareaR.value.trim().length
  }
});

//使用事件委托来实现时间的显示和隐藏
document.body.addEventListener('mouseenter', function (e) {
  if (e.target.closest('.timeMsg')) {
    if (e.target.querySelector('p')) {
      e.target.querySelector('p').classList.add('pactive')
    }

  }
}, true)

document.body.addEventListener('mouseleave', function (e) {
  if (e.target.closest('.timeMsg')) {
    if (e.target.querySelector('p')) {
      e.target.querySelector('p').classList.remove('pactive')
    }
  }
}, true)



//详情页面回复框显示
function closeRactive() {
  document.querySelectorAll('.ractive').forEach(item => {
    item.classList.remove('ractive')
  })

}

function errMsg(msg) {
  let dzErr = document.querySelector('.dzErr')
  dzErr.querySelector('span').textContent = msg
  dzErr.style.transform = 'translateY(0)'
  setTimeout(() => {
    dzErr.style.transform = 'translateY(-100px)'
  }, 3000)
}
function saveMsg(msg) {
  let saveMsg = document.querySelector('.saveMsg')
  saveMsg.querySelector('span').textContent = msg
  saveMsg.style.transform = 'translateY(0)'
  setTimeout(() => {
    saveMsg.style.transform = 'translateY(-100px)'
  }, 2000)
}
// function replyClick(e) {
//   let replyBtn = e.target.closest('.user-reply-footer span:nth-child(1), .son-reply-footer span:nth-child(1)')
//   if (!replyBtn) return
//   let replyBox = replyBtn.parentNode.nextElementSibling
//   if (!replyBtn.classList.contains('ractive') && !replyBox.classList.contains('ractive')) {
//     closeRactive()
//     replyBtn.classList.add('ractive')
//     replyBox.classList.add('ractive')
//     let text = document.querySelector('.ractive textarea')
//     text.value = ''
//     document.querySelector('.ractive .wordCount').textContent = text.value.length
//   } else {
//     let text = document.querySelector('.ractive textarea')
//     text.value = ''
//     document.querySelector('.ractive .wordCount').textContent = text.value.length
//     closeRactive()
//   }
//   if (replyBox.querySelector('textarea')) {
//     replyBox.querySelector('textarea').focus()
//   }
// }
// document.addEventListener('click', replyClick)
